import Tabs from '../components/tabs.vue';
import channelCom from '../components/channel.vue';

export default {
    name:'mx-navtab',
    components:{
        [Tabs.name]:Tabs,
        [channelCom.name]:channelCom,
    },
    data(){
        return {
            channel:{
                status:false,
                my:[],
                news:[],
                video:[],
                area:[],
            },
            htmlName: location.pathname.replace(/\/(.+)\.html/, '$1') + 'NowTag',
            onTag: '',
            country: this.$utils.caches.get('country', 'storage'),
            popInfo: {
                title: "",
                content: ""
            },
            alert: {
                status: false,
                item: "",
                name: ""
            },
            noChangeArea: this.$utils.caches.get('noChangeArea', 'storage'),
            countryName: '',
        }
    },
    methods:{
        confirm() {
            this.country = this.alert.shortName
            this.$utils.caches.set('country', this.country, 'storage')
            this.$utils.caches.set('noChangeArea', true, 'storage')
            this.alert.status = false;
            // this.initData();
            location.reload();
        },
        cancel () {
            this.alert.status = false;
            this.$utils.caches.set('noChangeArea', true, 'storage')
        },
        initTabs(){
            // 初始化tabs
            // let cacheTabs = this.$utils.caches.get(this.page.cache_channel_type);
            // try{
            //     cacheTabs = JSON.parse(cacheTabs);
            //     if(cacheTabs.length>0){
            //         this.updateTabData(cacheTabs);
            //     }
            // }catch(e){}
            if(!this.noChangeArea) {
                this.loadChannel();
            } else {
                let areaList = this.$utils.caches.get('area_list', 'storage')
                let oldCountry = JSON.parse(areaList).filter((i) => {
                    return i.short_name == this.country
                })
                if(!oldCountry.length){
                    this.loadChannel();
                }else{
                    this.countryName = oldCountry[0].name
                    this.initData();
                }
            }
        },
        updateTabData(tabs){
            this.channel.my = tabs;

            // 返回上一页，记住tag
            this.onTag = this.$utils.caches.get(this.htmlName, 'session');
            this.onTag = this.onTag ? JSON.parse(this.onTag) : {}; 

            if(this.onTag.index) {
                this.$refs.tabs.$emit('update',{active:this.onTag.index, list:this.channel.my});
            } else {
                this.$nextTick(()=>{
                    let index;
                    for(let i=0,len = tabs.length;i<len;i++){
                        let item = tabs[i];
                        if(item.short_name && item.short_name === this.page.country_short_name){
                            index = i;
                            break;
                        }else if(item.id === this.page.channel_id){
                            index = i;
                            break;
                        }
                    }
                    this.$refs.tabs.$emit('update',{active:index,list:this.channel.my});
                })
            }
        },
        getAreaByName(name){
            let area;
            for(let i = 0,len = this.channel.area.length;i<len;i++){
                let item = this.channel.area[i];
                if(item.name == name){
                    area = item;
                    break;
                }
            }
            return area;
        },
        loadChannel(){
            this.$http.get('?ct=index&ac=get_country').then(response=>{
                let {data} = response;
                if(data.code == 0){
                    let country = data.data.country;
                    let areaList = this.$utils.caches.get('area_list', 'storage')
                    if(this.country && this.country != country) {

                        let item = this.getAreaByName(country);
                        let nowCountry = JSON.parse(areaList).filter((i) => {
                            return i.short_name == country
                        })

                        let oldCountry = JSON.parse(areaList).filter((i) => {
                            return i.short_name == this.country
                        })

                        this.alert.name = nowCountry[0].name;
                        this.alert.shortName = nowCountry[0].short_name
                        this.alert.item = item;
                        this.alert.status = true;

                        this.country = oldCountry[0].short_name
                        this.countryName = oldCountry[0].name
                        this.initData();
                    } else {
                        this.country = country;
                        this.$utils.caches.set('country', this.country, 'storage')
                        this.initData();
                    }
                } else{
                    this.$toast(data.msg);
                }
            }).catch(e=>{
                this.$toast(e);
            })
        },
        initData () {
            return this.$http.get('?ct=index&ac=init&country='+ this.country).then(response=>{
                let {data} = response;
                if(data.code == 0){
                    let rs = data.data;
                    this.channel.news = rs.news_channel_list;
                    this.channel.video = rs.video_channel_list;
                    
                    rs.userid && this.$utils.caches.set('userid',rs.userid)
                    rs.version && this.$utils.caches.set('version',rs.version)
                    //为area添加short_name属性
                    let areaMap = {},
                        listMap = {};
                    let list = [];

                    switch(this.page.cache_channel_type){
                        case 'video_channel':
                        list = this.channel.video;
                            break;
                        case 'news_channel':
                        list = this.channel.news;
                            break;
                    }
                    
                    let myTab = []; 
                    
                    if(list.length > 0){
                        list.forEach(item=>{
                            item.type = "channel";
                            listMap[item.id] = item;
                            if(item.is_fix == 1 || item.is_default == 1){
                                myTab.push(item);
                            }
                        })
                    }
                    rs.area_list.forEach(item=>{
                        item.short_name = item.en_short_name;
                        item.type = "area";
                        areaMap[item.short_name] = item;
                        if(item.is_fix == 1 || item.is_default == 1){
                            myTab.push(item);
                        }

                        if(item.en_short_name == this.country) {
                            this.countryName = item.name
                        }
                    });

                    this.$utils.caches.set('area_list', JSON.stringify(rs.area_list), 'storage')

                    this.channel.area = rs.area_list;
                    
                    //读取用户选中数据
                    let userSelect = [];
                    let selectList;
                    switch(this.page.cache_channel_type){
                        case 'video_channel':
                            selectList = rs.select_video_channel.split(',');
                            break;
                        case 'news_channel':
                            selectList = rs.select_news_channel.split(',');
                            break;
                    }

                    selectList && selectList.forEach(item=>{
                        if(isNaN(item)){
                            if(areaMap[item]){
                                userSelect.push(areaMap[item])
                            }
                        }else{
                            if(listMap[parseInt(item)]){
                                userSelect.push(listMap[parseInt(item)])
                            }
                        }
                    })

                    if(userSelect.length>0) myTab = userSelect;
                
                    if(this.channel.my.length == 0){
                        this.updateTabData(myTab);
                        let selectItem = this.onTag.name ? this.onTag : myTab[0];
                        if(selectItem.type == 'channel'){
                            this.page.channel_id = selectItem.id
                        }else{
                            this.page.country_short_name = selectItem.short_name
                        }
                        this.changeTab(selectItem,false);
                    }

                    // if(this.page.area && !this.page.area.short_name){
                    //     try{
                    //         if(this.page.gps){
                    //             let item = this.getAreaByName(this.page.gps);
                    //             if(item){
                    //                 this.page.are = item;
                    //                 this.page.country_short_name = item.short_name
                    //             }else{
                    //                 throw new Error('empty')
                    //             }
                    //         }else{
                    //             throw new Error('empty')
                    //         }
                    //     }catch(e){
                    //         this.page.area = data.data.location;
                    //         // this.page.country_short_name = data.data.location.short_name;
                    //     }

                    //     this.$utils.caches.set('area',JSON.stringify(this.page.area));
                    // }

                    // this.areaDone(this.alert.item);  
                    this.$emit('RELOADDATA','init');
                }else{
                    this.$toast(data.msg);
                }
            }).catch(e=>{
                this.$toast(e);
            })
        },
        changeTab(tab,reload = true){
            if(tab.short_name){//地区
                if(tab.short_name !== this.page.country_short_name || !reload){
                    this.page.area = tab;
                    this.page.channel_id = '';
                    this.page.country_short_name = tab.short_name;
                    reload && this.$emit('RELOADDATA','channelChange');
                }
            }else {//普通频道
                if(tab.id !== this.page.channel_id || !reload){
                    this.page.area = {};
                    this.page.country_short_name = '';
                    this.page.channel_id = tab.id;
                    reload && this.$emit('RELOADDATA','channelChange');
                }
            }
        },
        channelChange(newList){
            this.channel.status = false;
            if(JSON.stringify(newList) == JSON.stringify(this.channel.my)) return false;
            
            let countrys = [],channel_ids = [],channel_sort=[];
            newList.forEach(item=>{
                if(item.type == 'channel'){
                    channel_sort.push(item.id);
                    channel_ids.push(item.id);
                }else if(item.type == 'area'){
                    channel_sort.push(item.short_name);
                    countrys.push(item.short_name);
                }
            })

            this.$http.post('?ct=member&ac=change_select_channel',{
                type:this.page.cache_channel_type == 'news_channel' ? 0 : 1,
                countrys:countrys.join(','),
                channel:channel_ids.join(','),
                sort_channels:channel_sort.join(',')
            }).then(response=>{
                let {data} = response;
                if(data.code !== 0){
                    this.$toast(data.msg);
                }
            }).catch(e=>{
                window.$zEvent.$emit('ERROR',e);
                this.$toast(e);
            })

            this.updateTabData(newList)
            // this.$refs.tabs.$emit('update',{active:this.page.channel_id,list:this.channel.my});
            this.$nextTick(()=>{
                this.$emit('RELOADDATA','channelChange');
            })
            //频道修改的情况下，当前频道修改时触发刷新
            // if(oldChannelId !== this.page.channel_id){
                // this.$emit('RELOADDATA','channelChange');
            // }

        },
    }
}